from flask import Flask, flash, redirect, url_for, \
    request, render_template, make_response, \
    session, abort

from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
# 上传文件的目录
UPLOAD_FOLDER = 'pic'
# 上传文件允许的扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000


# 无参路由
@app.route('/hello_world')
def hello_world():
    return 'Hello World!'


# 传入int
@app.route('/get_id/<int:id>')
def get_id(id):
    result = '您出入的id是：%d' % id
    return result


# 传入字符
@app.route('/get_name/<name>')
def get_name(name):
    return '您出入的name是：%s' % name


# 传入float
@app.route('/get_float/<float:float>')
def get_float(float):
    result = '您出入的float是：%f' % float
    return result


# url_for
@app.route('/get_url_for/<name>')
def get_url_for(name):
    # url_for中第一个参数是方法名，
    # 第二个参数，键是目标路由接收参数的名称，值是传递的参数。
    if name == "tom":
        return redirect(url_for("hello_world"))
    else:
        return redirect(url_for("get_name", name=name))


# set cookie， 设置cookie
@app.route('/set_cookie')
def set_cookie():
    rsp = make_response("success")
    rsp.set_cookie('flask', 'flask', max_age=3600)
    return rsp


# get cookie
@app.route('/get_cookie')
def get_cookie():
    cookie = request.cookies.get('flask')
    return cookie


# delete cookie
@app.route('/del_cookie')
def del_cookie():
    rsp = make_response('del success')
    rsp.delete_cookie('flask')
    return rsp


# 设置session
@app.route('/set_session')
def set_session():
    session['username'] = 'haibt'
    pass


# 删除session
@app.route('/del_session')
def del_session():
    session.pop('username')
    pass


# 定义一个密钥
app.secret_key = 'flask'


# 跳转login页面
@app.route('/to_login')
def to_login():
    return render_template('login.html')


# 判断文件是否合法
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# 表单提交测试
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 获取post请求表单数据
        name = request.form['name']
        if name is not None:
            session['username'] = name
        files = request.files
        print("files: ", files)
        if 'file' not in files:
            flash('no file part')
            return redirect(request.url)
        file = files['file']
        # 如果用户不选择文件，会提交一个空的文件过来，并且没有文件名称
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            # 生成随机数
            uuid = os.urandom(16)

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return render_template('index.html', str=filename)
        return redirect(url_for('/to_login', name=name))
    if request.method == 'GET':
        # 获取get请求参数
        name = request.args.get('name')
        return redirect(url_for('get_name', name=name))


# 登出
@app.route('/logout')
def logout():
    session.pop('username')
    return render_template('login.html')


# index
@app.route('/index', methods=['GET', 'POST'])
def index():

    # 显示用户名和头像
    name = ''
    file = ''
    # 测试数据
    str = 'str'
    int = 321
    bool = True
    str_list = ['a', 'b', 'c', 'd']
    int_list = [1, 2, 3, 4]
    object = {
        'name': 'tom',
        'age': 18
    }
    return render_template('index.html',
                           str=str,
                           int=int,
                           bool=bool,
                           str_list=str_list,
                           int_list=int_list,
                           object=object)


# session
@app.route('/')
def home():
    if 'username' in session:
        username = session['username']
        if username != 'admin':
            app.logger.error("无权访问。")
            abort(401)
        return '登录用户名是:' + username + '<br>' + \
               "<b><a href = '/logout'>点击这里注销</a></b>"
    return "您暂未登录， <br><a href = '/to_login'></b>" + \
           "点击这里登录</b></a>"


if __name__ == '__main__':
    app.run(debug=True)
